<template>
  <a-modal
    v-model:open="modalOpen"
    title="修改密码"
    :width="500"
    :closable="true"
    :mask-closable="true"
    :mask="true"
    :z-index="1000"
    :centered="true"
    @cancel="handleCancel"
    @ok="handleCancel"
  >
    <div class="change-password-container">
      <a-form :model="passwordForm" layout="vertical">
        <a-form-item 
          label="旧密码" 
          name="oldPassword"
          :rules="[
            { required: !isForceChange, message: '请输入旧密码' }
          ]"
        >
          <a-input-password
            v-model:value="passwordForm.oldPassword"
            size="large"
            placeholder="请输入旧密码"
            :disabled="isForceChange"
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
          <template #extra v-if="isForceChange">
            <span class="force-change-tip">首次登录需要修改密码，无需输入旧密码</span>
          </template>
        </a-form-item>

        <a-form-item 
          label="新密码" 
          name="newPassword"
          :rules="[
            { required: true, message: '请输入新密码' },
            { min: 6, message: '密码长度至少6位' }
          ]"
        >
          <a-input-password
            v-model:value="passwordForm.newPassword"
            size="large"
            placeholder="请输入新密码"
          >
            <template #prefix>
              <KeyOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item 
          label="确认新密码" 
          name="confirmPassword"
          :rules="[
            { required: true, message: '请确认新密码' },
            { validator: validateConfirmPassword, message: '两次输入的密码不一致' }
          ]"
        >
          <a-input-password
            v-model:value="passwordForm.confirmPassword"
            size="large"
            placeholder="请再次输入新密码"
          >
            <template #prefix>
              <KeyOutlined />
            </template>
          </a-input-password>
        </a-form-item>
      </a-form>
    </div>

    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit" :loading="submitting">
        确认修改
      </a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { LockOutlined, KeyOutlined } from '@ant-design/icons-vue'
import { updatePassword } from '@/api/user/sysUserController'
import { useAuthStore } from '@/stores/authStore'

interface Props {
  open: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'password-changed'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const authStore = useAuthStore()

// 计算属性用于v-model:open
const modalOpen = computed({
  get: () => props.open,
  set: (value: boolean) => emit('update:open', value)
})

// 表单数据
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 提交状态
const submitting = ref(false)

// 是否强制修改密码
const isForceChange = computed(() => {
  return authStore.userInfo?.forcePasswordChange === true
})

// 验证确认密码
const validateConfirmPassword = () => {
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    return Promise.reject('两次输入的密码不一致')
  }
  return Promise.resolve()
}

// 提交修改密码
const handleSubmit = async () => {
  try {
    submitting.value = true
    
    // 构建请求数据
    const requestData = {
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword
    }
    
    const result = await updatePassword(requestData)
    console.log('修改密码结果:', result)
    
    if ((result as any).code === '00000') {
      message.success('密码修改成功！请重新登录')
      
      // 清除本地存储的认证信息
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 重置 authStore 状态
      authStore.token = ''
      authStore.userInfo = null
      
      // 关闭模态框
      handleCancel()
      
      // 触发密码修改成功事件
      emit('password-changed')
      
      // 延迟跳转到登录页面
      setTimeout(() => {
        window.location.href = '/'
      }, 1500)
    } else {
      // 处理业务逻辑错误
      const errorMsg = (result as any).msg || '密码修改失败'
      message.error(errorMsg)
    }
  } catch (error: any) {
    console.error('密码修改失败:', error)
    
    // 处理不同类型的错误
    let errorMessage = '密码修改失败，请重试'
    
    if (error.response) {
      // 服务器返回了错误状态码
      const { status, data } = error.response
      console.log('错误状态码:', status, '错误数据:', data)
      
      if (data?.msg) {
        errorMessage = data.msg
      } else if (data?.message) {
        errorMessage = data.message
      } else {
        switch (status) {
          case 400:
            errorMessage = '请求参数错误'
            break
          case 401:
            errorMessage = '登录已过期，请重新登录'
            break
          case 403:
            errorMessage = '没有权限执行此操作'
            break
          case 500:
            errorMessage = '服务器内部错误'
            break
          default:
            errorMessage = `请求失败 (${status})`
        }
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      errorMessage = '网络连接失败，请检查网络设置'
    } else {
      // 请求配置错误
      errorMessage = error.message || '请求配置错误'
    }
    
    message.error(errorMessage)
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  // 重置表单
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  emit('update:open', false)
}

// 监听弹窗显示状态
onMounted(() => {
  // 如果是强制修改密码，清空旧密码字段
  if (isForceChange.value) {
    passwordForm.value.oldPassword = ''
  }
})
</script>

<style scoped>
.change-password-container {
  padding: 20px 0;
}

.force-change-tip {
  color: #ff6b6b;
  font-size: 12px;
}
</style>
